package com.Policing.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Adapter.Public_list_item_Adapter;
import com.Policing.Facility_Maintenance.Facility_Maintenance;
import com.Policing.Since_case.Since_case;
import com.demo.WaveSwipeRefreshLayout;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.bean.MainService_bean;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import java.io.IOException;
import java.util.*;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/4/27.
 */

public class Maintenance_service extends Fragment {
    private ImageView opmune;
    private String id;
    private  List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String url="http://"+ Ip_Set.IP+"/api/deviceMainRepairQuery";
    private Handler handler = new Handler();
    private ListView lv_list;
    private TextView title_text;
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private SlideSideMenuExampleActivity mainActivity;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.maintenance_service, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        SharedPreferences mm = mainActivity.getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        inview();

    }

    private void inview() {
        title_text = (TextView) mainActivity.findViewById(R.id.title_text);
        title_text.setText("设备维修");
        lv_list = (ListView) mainActivity.findViewById(R.id.record);
        opmune = (ImageView) mainActivity.findViewById(R.id.opmenu);
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        //mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                //模拟3秒的加载过程
                new Handler().postDelayed(() -> {
                    post();
                    mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                    //接下来可以刷新ListView
                }, 1200);


            }

        });
        lv_list.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(mainActivity, Facility_Maintenance.class);
            intent.putExtra("maintainId", String.valueOf(list.get(position).get("odd")));
            intent.putExtra("part", String.valueOf(list.get(position).get("creator")));
            intent.putExtra("deviceNumber", String.valueOf(list.get(position).get("sum")));
            intent.putExtra("deviceName",String.valueOf(list.get(position).get("scope")));
            startActivity(intent);

        });
        opmune.setOnClickListener(v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
    }
    public void post() {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("userId",id)
                    .add("source", Since_case.set().getSource()); //传递键值对参数
            final Request request = new Request.Builder()//创建Request 对象。
                    .url(url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    handler.post(() -> {
                        Toast.makeText(mainActivity,"请连接网络后重试",Toast.LENGTH_SHORT).show();
                        mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                        Log.i("123123", "error");
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    final String responseData = response.body().string();
                    handler.post(() -> {
                        list.clear();
                        Public_list_item_Adapter re_ad1 = new Public_list_item_Adapter(mainActivity,list);
                        lv_list.setAdapter(re_ad1);
                        Log.i("datadata",responseData);
                        if (responseData.equals("[]")){
                            Toast.makeText(mainActivity,"无异常计划",Toast.LENGTH_SHORT).show();
                            return;}
                        mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                        Gson gson = new Gson();
                        List<MainService_bean> userList = gson.fromJson(responseData, new TypeToken<List<MainService_bean>>(){}.getType());
                        for(int i = 0;i < userList.size();i++){
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv","保养单号");
                            map.put("creator_tv","零件");
                            map.put("sum_tv","设备编号");
                            map.put("state_tv","保养时间");
                            map.put("scope_tv","设备名称");
                            map.put("Date_created_tv","");
                            map.put("Inventory_date_tv","");


                            map.put("odd",userList.get(i).getMaintainId());
                            map.put("scope",userList.get(i).getDeviceName());
                            map.put("state",userList.get(i).getDate().substring(0,10));
                            map.put("Date_created","");
                            map.put("sum",userList.get(i).getDeviceNumber());
                            map.put("creator",userList.get(i).getPart());
                            map.put("Inventory_date","");
                            list.add(map);
                            Collections.reverse(list);
                        }
                        Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity,list);
                        lv_list.setAdapter(re_ad);
                    });

                }
            });

        }).start();

    }
    @Override
    public void onStart() {
        //模拟3秒的加载过程
        new Handler().postDelayed(() -> post(), 400);
        super.onStart();
    }
}
